/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package BackingBeans;

import Facebook.FacebookClientLocal;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.faces.application.FacesMessage;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.SessionScoped;
import javax.faces.context.FacesContext;
import javax.naming.InitialContext;
import javax.naming.NamingException;
import javax.servlet.http.HttpServletRequest;
import smartgrid.Contract;
import smartgrid.Contracts;
import smartgrid.FacebookAccountInterface;
import smartgrid.Supplier;
import smartgrid.SuppliersInfo;
import smartgrid.exceptions.ContractAlreadyExistsException;
import smartgrid.exceptions.FacebookAccountDisabledException;
import smartgrid.exceptions.FacebookAccountNotExistException;
import smartgrid.exceptions.InvalidContractNifException;
import smartgrid.exceptions.InvalidContractNumberException;

/**
 *
 * @author claudio
 */
@ManagedBean
@SessionScoped
public class ContaBackingBean {

    private Map<String, Contract> Contracts;
    private Map<String, Supplier> Suppliers;
    private String SelectedSupplier;
    private String SelectedContract;
    private String UserName;
    private String Contract;
    private String Nif;

    /** Creates a new instance of ContaBackingBean */
    public ContaBackingBean() {
        this.Contracts = new HashMap<String, Contract>();
        try {
            InitialContext initCtx = new InitialContext();
            Contracts si = (Contracts) initCtx.lookup("java:global/SmartGridEA/ContractsManager");

            FacebookAccountInterface fm = (FacebookAccountInterface) initCtx.lookup("java:global/SmartGridEA/FacebookAccountManager");

            HttpServletRequest request = (HttpServletRequest) FacesContext.getCurrentInstance().getExternalContext().getRequest();
            FacebookClientLocal fbl = null;
            if (request != null) {
                fbl = (FacebookClientLocal) request.getSession(true).getAttribute("facebook");
                if (fbl != null) {
                    this.UserName = fbl.getNome();
                }
            }

            
            List<Contract> ss = si.getContracts(fm.getFacebookAccountByUID(fbl.getUId()));
            if (ss != null) {
                System.out.println("NOT NULL");
                for (Contract s : ss) {
                    this.Contracts.put(s.getNumber(), s);
                }
                this.SelectedContract = ss.get(0).getNumber();
            }
        } catch (FacebookAccountDisabledException ex) {
            Logger.getLogger(ContaBackingBean.class.getName()).log(Level.SEVERE, null, ex);
        } catch (NamingException ex) {
            Logger.getLogger(UnregisteredBackingBean.class.getName()).log(Level.SEVERE, null, ex);
        }
        this.Suppliers = new HashMap<String, Supplier>();
        try {
            InitialContext initCtx = new InitialContext();
            SuppliersInfo si = (SuppliersInfo) initCtx.lookup("java:global/SmartGridEA/SuppliersManager");

            List<Supplier> ss = si.getSuppliers();
            if (ss != null) {
                System.out.println("NOT NULL");
                for (Supplier s : ss) {
                    this.Suppliers.put(s.getName(), s);
                }
            }
        } catch (NamingException ex) {
            Logger.getLogger(UnregisteredBackingBean.class.getName()).log(Level.SEVERE, null, ex);
        }

    }

    public void refreshContractList() {
        this.Contracts = new HashMap<String, Contract>();
        try {
            InitialContext initCtx = new InitialContext();
            Contracts si = (Contracts) initCtx.lookup("java:global/SmartGridEA/ContractsManager");

            FacebookAccountInterface fm = (FacebookAccountInterface) initCtx.lookup("java:global/SmartGridEA/FacebookAccountManager");

            HttpServletRequest request = (HttpServletRequest) FacesContext.getCurrentInstance().getExternalContext().getRequest();
            FacebookClientLocal fbl = null;
            if (request != null) {
                fbl = (FacebookClientLocal) request.getSession(true).getAttribute("facebook");
                if (fbl != null) {
                    this.UserName = fbl.getNome();
                }
            }

            List<Contract> ss = si.getContracts(fm.getFacebookAccountByUID(fbl.getUId()));
            if (ss != null) {
                System.out.println("NOT NULL");
                for (Contract s : ss) {
                    this.Contracts.put(s.getNumber(), s);
                }
                this.SelectedContract = ss.get(0).getNumber();
            }
        } catch (FacebookAccountDisabledException ex) {
            Logger.getLogger(ContaBackingBean.class.getName()).log(Level.SEVERE, null, ex);
        } catch (NamingException ex) {
            Logger.getLogger(UnregisteredBackingBean.class.getName()).log(Level.SEVERE, null, ex);
        }
        
        this.Contract = "";
        this.Nif = "";
    }

    public Set<String> getContractList() {
        return this.Contracts.keySet();
    }

    public String getSelectedContract() {
        return SelectedContract;
    }

    public Set<String> getSuppliersList() {
        return Suppliers.keySet();
    }

    public void setSelectedContract(String SelectedContract) {
        this.SelectedContract = SelectedContract;
    }

    public Map<String, Contract> getSuppliers() {
        return Contracts;
    }

    public String getUserName() {
        return UserName;
    }

    public void setUserName(String UserName) {
        this.UserName = UserName;
    }

    public String getContractNif() {
        Contract c = this.Contracts.get(this.SelectedContract);
        return c.getClientNif();
    }

    public String getContract() {
        return Contract;
    }

    public void setContract(String Contract) {
        this.Contract = Contract;
    }

    public Map<String, Contract> getContracts() {
        return Contracts;
    }

    public void setContracts(Map<String, Contract> Contracts) {
        this.Contracts = Contracts;
    }

    public String getNif() {
        return Nif;
    }

    public void setNif(String Nif) {
        this.Nif = Nif;
    }

    public String getSelectedSupplier() {
        return SelectedSupplier;
    }

    public void setSelectedSupplier(String SelectedSupplier) {
        this.SelectedSupplier = SelectedSupplier;
    }

    public void setSuppliers(Map<String, Supplier> Suppliers) {
        this.Suppliers = Suppliers;
    }

    public String getContractName() {
        Contract c = this.Contracts.get(this.SelectedContract);
        return c.getClientName();
    }

    public String getContractNumber() {
        Contract c = this.Contracts.get(this.SelectedContract);
        return c.getNumber();
    }

    public String getContractTarif() {
        Contract c = this.Contracts.get(this.SelectedContract);
        return c.getTariff_CurrentTarif_role().getName();
    }

    public String getContractSupplier() {
        Contract c = this.Contracts.get(this.SelectedContract);
        return c.getSupplier_role().getName();
    }

    private boolean validateEmpty() {
        boolean ret = true;
        FacesContext ctx = FacesContext.getCurrentInstance();

        if (this.Contract == null || this.Contract.isEmpty()) {
            FacesMessage msg = new FacesMessage();
            msg.setSeverity(FacesMessage.SEVERITY_WARN);
            msg.setSummary("Deve preencher o número do contrato.");
            msg.setDetail("Deve preencher o número do contrato.");
            ctx.addMessage("contractform:contract", msg);
            ret = false;
        }

        if (this.Nif == null || this.Nif.isEmpty()) {
            FacesMessage msg = new FacesMessage();
            msg.setSeverity(FacesMessage.SEVERITY_WARN);
            msg.setSummary("Deve preencher o número de contribuinte.");
            msg.setDetail("Deve preencher o número de contribuinte.");
            ctx.addMessage("contractform:nif", msg);
            ret = false;
        }
        return ret;
    }

    public String submit() throws InvalidContractNifException, ContractAlreadyExistsException, FacebookAccountNotExistException {
        FacesContext ctx = FacesContext.getCurrentInstance();
        if (!this.validateEmpty()) {
            return "";
        } else {
            try {
                HttpServletRequest request = (HttpServletRequest) FacesContext.getCurrentInstance().getExternalContext().getRequest();
                FacebookClientLocal fbl = (FacebookClientLocal) request.getSession(true).getAttribute("facebook");
                if (fbl == null) {
                    return "error";
                }

                InitialContext initCtx = new InitialContext();
                FacebookAccountInterface fb = (FacebookAccountInterface) initCtx.lookup("java:global/SmartGridEA/FacebookAccountManager");

                Contracts cm = (Contracts) initCtx.lookup("java:global/SmartGridEA/ContractsManager");

                Supplier s = this.Suppliers.get(this.SelectedSupplier);
                try {
                    cm.addContractToFacebookAccount(fbl.getUId(), s.getID(), this.Contract, this.Nif);
                } catch (InvalidContractNifException ex) {
                    FacesMessage msg = new FacesMessage();
                    msg.setSeverity(FacesMessage.SEVERITY_WARN);
                    msg.setSummary("O Nif não corresponde a este contrato.");
                    msg.setDetail("O Nif não corresponde a este contrato.");
                    ctx.addMessage("contractform:nif", msg);
                    return "";
                } catch (InvalidContractNumberException ex) {
                    FacesMessage msg = new FacesMessage();
                    msg.setSeverity(FacesMessage.SEVERITY_WARN);
                    msg.setSummary("O contrato que inseriu não é válido.");
                    msg.setDetail("O contrato que inseriu não é válido.");
                    ctx.addMessage("contractform:contract", msg);
                    return "";
                } catch (ContractAlreadyExistsException ex) {
                    FacesMessage msg = new FacesMessage();
                    msg.setSeverity(FacesMessage.SEVERITY_WARN);
                    msg.setSummary("O contrato que inseriu já está associado à conta facebook.");
                    msg.setDetail("O contrato que inseriu já está associado à conta facebook.");
                    ctx.addMessage("contractform:contract", msg);
                    return "";
                } catch (FacebookAccountNotExistException ex) {
                    return "error";
                }

            } catch (NamingException ex) {
                Logger.getLogger(UnregisteredBackingBean.class.getName()).log(Level.SEVERE, null, ex);
            }

            refreshContractList();

            return "";
        }
    }
}
